package com.wjj.common.mybatis.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.mybatisflex.annotation.UpdateListener;
import com.wjj.common.core.exception.ServiceException;
import com.wjj.common.mybatis.core.domain.BaseEntity;
import com.wjj.common.satoken.utils.LoginHelper;

import java.util.Date;

/**
 * @author wujunjie
 * @version 1.0
 * @date 2025/07/28 - 8:51
 */
public class MybatisUpdateListener implements UpdateListener {
    @Override
    public void onUpdate(Object metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject instanceof BaseEntity baseEntity) {
                // 获取当前时间作为更新时间，无论原始对象中的更新时间是否为空都填充
                Date current = new Date();
                baseEntity.setUpdateTime(current);

                // 获取当前登录用户的ID，并填充更新人信息
                Long userId = LoginHelper.getUserId();
                if (ObjectUtil.isNotNull(userId)) {
                    baseEntity.setUpdateBy(userId);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
